package 重温_Java并发基础.CompletableFuture案例.异步案例;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author idea
 * @data 2020/2/22
 */
public class StockSupplier implements Supplier<String> {

    @Override
    public String get() {
        int no = -1;
        String result = getResult(no);
        return result;
    }


    private String getResult(int no) {
        if (no < 0) {
            throw new RuntimeException("run has exception");
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return no + "no";
    }


    public static void main(String[] args) throws InterruptedException {
        //异步执行的案例1
        CompletableFuture<String> completableFuture=CompletableFuture.supplyAsync(new StockSupplier());
        //当完成的时候
        completableFuture.thenAccept(new Consumer<String>() {
            @Override
            public void accept(String str) {
                System.out.println("计算完毕:"+str);
            }
        });
        //有异常的时候
        completableFuture.exceptionally(new Function<Throwable, String>() {
            @Override
            public String apply(Throwable throwable) {
//                System.out.println("error:"+throwable.getMessage());
                return "error msg";
            }
        });
        while(true){
            TimeUnit.SECONDS.sleep(2);
            System.out.println("come on");
        }
        //注意CompletableFuture 默认使用了线程池，会在主线程结束的时候关闭
//        completableFuture.join();
    }
}
